package cn.com.yangzhenyu;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ObjectStream {

    public static void main(String[] args) {
        List<A> stuList = new ArrayList<A>();
        stuList.add(new A(10,"猜猜看"));
        stuList.add(new A(100,"试试看"));
        ObjectStream os = new ObjectStream();
        try {
            os.writerObject(stuList, "d://data.json");
            Object obj = os.readObject("d://data.json");
            List<A> retList = (List)obj;
            for (A a : retList) {
                System.out.println(a);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writerObject(Object obj, String path) throws IOException {
        ObjectOutputStream objOP = null;
        try {
            // 1.创建目标路径
            File file = new File(path);
            // 2.创建流通道
            FileOutputStream fos = new FileOutputStream(file);
            // 3.创建对象输出流
            objOP = new ObjectOutputStream(fos);
            // 5.向目标路径文件写入对象
            objOP.writeObject(obj);
            // 6.关闭资源
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            objOP.close();
        }
    }

    public Object readObject(String path) throws IOException {
        ObjectInputStream objIP = null;
        Object retObj = null;
        try {
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            objIP = new ObjectInputStream(fis);
            retObj = objIP.readObject();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            objIP.close();
        }
        return retObj;
    }
}
